<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="角色名称">
              <a-input placeholder="请输入" v-model="queryParam.roleName"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchQueryParamBtn()">重置</a-button>
              <a-button type="danger" style="margin-left: 8px" @click="newRole">新增</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <s-table
      ref="table"
      row-key="id"
      size="default"
      :columns="columns"
      :data="loadData"
      :expandedRowKeys="expandedRowKeys"
      @expand="handleExpand"
    >
      <div
        slot="expandedRowRender"
        slot-scope="record"
        style="margin: 0">
        <a-row
          :style="{ marginBottom: '10px' }">
          <a-col :span="12" v-for="(menu, index) in record.menuList" :key="index" :style="{ marginBottom: '12px', height: '23px' }">
            <a-col :lg="6" :md="24">
              <span>{{ menu.menuName }}：</span>
            </a-col>
            <a-col :lg="18" :md="24" v-if="menu.buttonList && menu.buttonList.length > 0">
              <a-tag color="cyan" v-for="button in menu.buttonList" :key="button.buttonId">{{ button.buttonName }}</a-tag>
            </a-col>
            <a-col :span="20" v-else>-</a-col>
          </a-col>
        </a-row>
      </div>
      <a-tag color="blue" slot="state" slot-scope="text">{{ text | statusFilter }}</a-tag>
      <span slot="createTime" slot-scope="text">{{ text | moment }}</span>
      <span slot="action" slot-scope="text, record">
        <a @click="handleEdit(record)">编辑</a>
        <a-divider type="vertical" />
        <a href="javascript:;" @click="delRole(record)">删除</a>
        <!--<a-dropdown>-->
          <!--<a class="ant-dropdown-link">-->
            <!--更多 <a-icon type="down" />-->
          <!--</a>-->
          <!--<a-menu slot="overlay">-->
            <!--<a-menu-item>-->
              <!--<a href="javascript:;">详情</a>-->
            <!--</a-menu-item>-->
            <!--<a-menu-item>-->
              <!--<a href="javascript:;" @click="delRole(record)">删除</a>-->
            <!--</a-menu-item>-->
          <!--</a-menu>-->
        <!--</a-dropdown>-->
      </span>
    </s-table>

    <a-modal
      :title="modal.title"
      style="top: 20px;"
      :width="1000"
      v-model="modal.visible"
      :confirm-loading="modal.loading"
      @ok="handleOk"
    >
      <a-form class="permission-form" :form="form">

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          style="display: none"
        >
          <a-input
            v-decorator="['id']"
          />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="角色名称"
        >
          <a-input
            placeholder="起一个名字"
            v-decorator="[
              'roleName',
              {
                rules: [
                  {
                    required: true,
                    message: '请填写角色名称'
                  },
                  {
                    max: 20,
                    message: '角色名称长度必须小于20位'
                  }
                ]
              }
            ]"
          />
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="状态"
        >
          <a-select
            v-decorator="[
              'state',
              {rules: [{ required: true, message: '请选择状态' }]}]"
            placeholder="请选择状态">
            <a-select-option value="1">启用</a-select-option>
            <a-select-option value="2">禁用</a-select-option>
          </a-select>
        </a-form-item>

        <a-divider>拥有权限</a-divider>
        <template v-for="menu in menuList">
          <a-form-item
            class="permission-group"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :key="menu.id"
            :label="menu.menuName"
          >
            <a-checkbox :indeterminate="indeterminate[menu.id]" :checked="checkAll[menu.id]" @change="onCheckAllChange($event, menu.id)">全选</a-checkbox>
            <a-checkbox-group v-decorator="[`menu.${menu.id}`]" :options="menu.buttonOption" @change="onChangeOption($event, menu.id)"/>
          </a-form-item>
        </template>

      </a-form>
    </a-modal>

  </a-card>
</template>

<script>
  import { STable } from '@/components'
  import { GetRoleList, SaveRole, DelRole } from '../../api/systemAdmin'
  import { PERMISSION_ENUM } from '@/utils/helper/permission'
  import { PageMenu, Buttons } from '../../api/common'

  const STATUS = {
    1: '启用',
    2: '禁用'
  }

  const columns = [
    {
      title: '角色名称',
      dataIndex: 'roleName'
    },
    {
      title: '状态',
      dataIndex: 'state',
      scopedSlots: { customRender: 'state' }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      scopedSlots: { customRender: 'createTime' },
      sorter: true
    },
    {
      title: '操作',
      width: '150px',
      dataIndex: 'action',
      scopedSlots: { customRender: 'action' }
    }
  ]

  export default {
    name: 'Role',
    components: {
      STable
    },
    data () {
      return {
        modal: {
          title: '',
          visible: false,
          loading: false,
          editType: 0 // 0 新增状态， 1 编辑状态
        },
        indeterminate: {},
        checkAll: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        form: this.$form.createForm(this),
        menuList: [],
        buttonAllList: [],

        // 查询参数
        queryParam: {},
        // 表头
        columns,
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          return GetRoleList(Object.assign(parameter, this.queryParam))
            .then(res => {
              console.log('getRoleList', res)
              if (res.code === 200) {
                return res.result
              } else {
                this.$message.error('获取列表数据出错！')
                return []
              }
            })
        },

        expandedRowKeys: [],
        selectedRowKeys: [],
        selectedRows: []
      }
    },
    filters: {
      statusFilter (key) {
        return STATUS[key]
      },
      permissionFilter (key) {
        const permission = PERMISSION_ENUM[key]
        return permission && permission.label
      }
    },
    computed: {
    },
    created () {
      Buttons().then(res => {
        console.log('buttons', res)
        if (res.code === 200) {
          this.buttonAllList = res.result
        } else {
          this.$message.error('查询按钮列表出错！')
        }
      })
      PageMenu().then(res => {
        console.log('PageMenu', res)
        this.menuList = res.result.map(menu => {
          const buttonOption = menu.buttonInfoList.map(button => {
            return {
              label: button.buttonName,
              value: button.buttonId
            }
          })
          return {
            ...menu,
            buttonOption
          }
        })
        for (let i = 0; i < this.menuList.length; i++) {
          this.indeterminate[this.menuList[i].id] = false
          this.checkAll[this.menuList[i].id] = false
        }
        console.log('menuList', this.menuList)
      })
    },
    methods: {
      buttonList (menuId) {
        if (menuId !== undefined) {
          return this.menuList.filter(v => v.id === menuId)[0].buttonOption.map(item => {
            return item.value
          })
        } else {
          return undefined
        }
      },
      newRole () {
        this.modal.title = '新增角色'
        this.form.resetFields()
        this.modal.loading = false
        this.modal.editType = 0
        for (let i = 0; i < this.menuList.length; i++) {
          this.indeterminate[this.menuList[i].id] = false
          this.checkAll[this.menuList[i].id] = false
        }
        this.modal.visible = true
        console.log(this.indeterminate)
        console.log(this.checkAll)
      },
      handleEdit (record) {
        this.form.resetFields()
        for (let i = 0; i < this.menuList.length; i++) {
          this.indeterminate[this.menuList[i].id] = false
          this.checkAll[this.menuList[i].id] = false
        }
        this.modal.title = '修改角色'
        this.modal.loading = false
        this.modal.editType = 1
        this.modal.visible = true
        console.log('edit record', record)
        const buttonList = {}
        record.menuList.forEach(row => {
          const groupKey = 'menu.' + row.menuId
          buttonList[groupKey] = row.buttonList.map(item => { return item.buttonId })
          this.onChangeOption(row.buttonList, row.menuId)
        })

        this.$nextTick(() => {
          this.form.setFieldsValue({
            'id': record.id,
            'roleName': record.roleName,
            'state': record.state
          })
          this.form.setFieldsValue(buttonList)
        })
      },
      handleOk (e) {
        e.preventDefault()
        this.modal.loading = true
        this.form.validateFields((err, values) => {
          console.log(values)
          if (err == null) {
            setTimeout(() => {
              const menu = []
              Object.keys(values.menu).forEach(menuId => {
                if (values.menu[menuId] !== undefined) {
                  menu.push({
                    menuId: parseInt(menuId),
                    buttonList: values.menu[menuId]
                  })
                }
              })
              values['menu'] = menu
              console.log(values)
              SaveRole(values).then(res => {
                console.log(res)
                if (res.code === 200) {
                  if (res.msg.indexOf('成功') >= 0) {
                    this.$message.success('保存成功！')
                    this.$refs.table.refresh(true)
                    this.$store.dispatch('GetInfo')
                    this.$store.dispatch('setRoleNames') // 更新store保存数据
                    this.modal.loading = false
                    this.modal.visible = false
                  } else {
                    this.$message.error('保存失败！' + res.msg)
                    this.modal.loading = false
                  }
                } else {
                  this.$message.error('服务出错' + res.msg)
                  this.modal.loading = false
                }
              }).catch(e => {
                this.$message.error('保存失败！')
                this.modal.loading = false
                console.error(e)
              })
            }, 2000)
          } else {
            this.$message.error('存在非法输入！')
            setTimeout(() => {
              this.modal.loading = false
              this.$nextTick(() => { this.modal.loading = false })
            }, 500)
          }
        })
      },
      onChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      handleExpand (expanded, record) {
        if (expanded) {
          this.expandedRowKeys.push(record.id)
        } else {
          this.expandedRowKeys = this.expandedRowKeys.filter(item => record.id !== item)
        }
      },
      toggleAdvanced () {
        this.advanced = !this.advanced
      },
      onChangeOption (e, id) {
        // this.indeterminate[index] = !!e.length && e.length < this.menuList[index].buttonOption.map(v => { return v.value }).length
        this.indeterminate[id] = !!e.length && e.length < this.buttonList(id).length
        this.checkAll[id] = !!e.length && e.length === this.buttonList(id).length
      },
      onCheckAllChange (e, menuId) {
        const key = 'menu.' + menuId
        const obj = {}
        obj[key] = e.target.checked ? this.buttonList(menuId) : []
        this.form.setFieldsValue(obj)
        this.indeterminate[menuId] = false
        this.checkAll[menuId] = e.target.checked
      },
      delRole (record) {
        const _this = this
        this.$confirm({
          title: '确定删除这个角色么',
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk () {
            DelRole({ id: record.id }).then(res => {
              if (res.code === 200) {
                if (res.msg.indexOf('成功') >= 0) {
                  _this.$message.success('删除成功！')
                  _this.$store.dispatch('setRoleNames')
                  _this.$refs.table.refresh(true)
                } else {
                  _this.$message.error('删除失败！' + res.msg)
                }
              } else {
                _this.$message.error('服务出错' + res.msg)
              }
            })
          },
          onCancel () {
          }
        })
      },
      resetSearchQueryParamBtn () {
        this.queryParam = {}
        this.$refs.table.refresh(true)
      }
    },
    watch: {
    }
  }
</script>

<style lang="less" scoped>
  .permission-form {
    /deep/ .permission-group {
      margin-top: 0;
      margin-bottom: 0;
    }
  }

</style>
